<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="选择日期" prop="date">
        <el-date-picker v-model="dateTime" type="month" placeholder="请选择月份" @change="dateChange">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="供应商" prop="provide">
        <el-input v-model="queryParams.provide" placeholder="请输入供应商" clearable />
      </el-form-item>
      <el-form-item label="财务编号" prop="financeCode">
        <el-input v-model="queryParams.financeCode" placeholder="请输入财务编号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" filterable placeholder="请选择状态" clearable>
          <el-option v-for="item in closingStatus" :key="item.label" :label="item.value" :value="item.label">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['system:vendorPayment:add']">新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['system:vendorPayment:edit']">修改</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['system:vendorPayment:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5" style="display:flex">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['system:vendorPayment:export']">导出</el-button>
        <el-button size="mini" type="primary" icon="el-icon-download" @click="importExcelFun" :loading="loadingbtn"
          :disabled="this.rz === '已入账'" v-hasPermi="['system:vendorPayment:ExcelFun']">导入</el-button>
          <el-button size="mini" type="primary" icon="el-icon-download" @click="importUpData" :loading="loadingbtn"
          :disabled="this.rz === '已入账'" v-hasPermi="['system:vendorPayment:ExcelFun']">导入数据</el-button>
        <el-button type="primary" plain size="mini" icon="el-icon-notebook-2" :disabled="rzDisabled"
          @click="RecordedClick" v-hasPermi="['system:vendorPayment:Recorded']">{{ rz }}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      <div class="textNuM" v-if="this.allMoney > 0">开票总金额：<span class="kpNum"> {{ formatNumber(this.allMoney) }}</span>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="vendorPaymentList" @selection-change="handleSelectionChange" border>
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column prop="index" label="序号" width="55" align="center"></el-table-column>
      <el-table-column label="日期" align="center" prop="createTime" />
      <el-table-column label="财务编号" align="center" prop="financeCode" />
      <el-table-column label="供应商名称" align="center" prop="provide" />
      <el-table-column label="含税红冲" align="center" prop="taxRed">
        <template slot-scope="scope">
          <span class="textNum">{{ formatNumber(parseFloat(scope.row.taxRed).toFixed(2)) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="平台(销售)金额" align="center" prop="platformMoney">
        <template slot-scope="scope">
          <span class="textNum">{{ formatNumber(parseFloat(scope.row.platformMoney).toFixed(2)) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本期应付金额" align="center" prop="payableMoney">
        <template slot-scope="scope">
          <span style="color:red;float: right;">{{ formatNumber(parseFloat(scope.row.payableMoney).toFixed(2))
            }}</span>
        </template>
      </el-table-column>
      <el-table-column label="本期实付金额" align="center" prop="actMoney">
        <template slot-scope="scope">
          <span class="textNum">{{ formatNumber(parseFloat(scope.row.actMoney).toFixed(2)) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="未付金额" align="center" prop="unpaidMoney">
        <template slot-scope="scope">
          <span class="textNum">{{ formatNumber(parseFloat(scope.row.unpaidMoney).toFixed(2)) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="含税估价" align="center" prop="valuationTax">
        <template slot-scope="scope">
          <span class="textNum">{{ formatNumber(parseFloat(scope.row.valuationTax).toFixed(2)) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="利润" align="center" prop="status">
        <template slot-scope="scope">
          <span class="textNum">{{
      formatNumber(parseFloat(scope.row.platformMoney - scope.row.payableMoney).toFixed(2)) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最后更新时间" align="center" prop="updateTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDelete(scope.row.provide)">产品详情</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row.provide)">仓库详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="textTs">
      <span class="text">本期应付金额=本期实付金额+未付金额</span>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </div>


    <!-- 添加或修改供应商付款对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="850px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-row :gutter="10" class="mb8">
          <el-col :span="12">
            <el-form-item label="财务编号" prop="financeCode">
              <el-input v-model="form.financeCode" placeholder="请输入财务编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商" prop="provide">
              <el-input v-model="form.provide" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税红冲" prop="taxRed">
              <el-input v-model="form.taxRed" placeholder="请输入含税红冲" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="平台金额" prop="platformMoney">
              <el-input v-model="form.platformMoney" placeholder="请输入平台金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本期应付金额" prop="payableMoney">
              <el-input v-model="form.payableMoney" placeholder="请输入应付金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本期未付金额" prop="unpaidMoney">
              <el-input v-model="form.unpaidMoney" placeholder="请输入未付金额" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税估价" prop="valuationTax">
              <el-input v-model="form.valuationTax" placeholder="请输入含税估价" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="开票入账" :visible.sync="dialogVisible" width="30%" :show-close="false" :close-on-click-modal="false"
      :center="true">
      <div>
        <el-checkbox v-model="checked2"> <span>共 <span style="font-size:20px;margin:5px 0;">{{ total }}</span>
            个供应商</span></el-checkbox>
      </div>
      <div>
        <el-checkbox v-model="checked" style="margin-top:15px"> <span>入账总金额:<span style="font-size:20px;"> {{
      formatNumber(this.allMoney) }}</span> </span></el-checkbox>
      </div>
      <div>
        <el-checkbox style="margin-top:15px" v-model="checked1"><span
            style="color:red;">注意：请确认入账金额,一但入账后不得修改,不得再次提交入账申请</span></el-checkbox>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rzCancel">取 消</el-button>
        <el-button type="primary" @click="rzAffirm" :loading="rzLoading">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog style="margin-top:30vh" title="" :visible.sync="ShowVisible" width="40%" :show-close="false"
      :close-on-click-modal="false">
      <span>数据正在导入中……</span>
    </el-dialog>


  </div>
</template>

<script>

import {getMonthlyStorageOutApi, listVendorPayment, excelUpload, getVendorPayment, delVendorPayment, addVendorPayment, updateVendorPayment } from "@/api/system/vendorPayment";
import { insertByProvideRevords, wareList } from "@/api/system/Recorded"
export default {
  name: "VendorPayment",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 供应商付款表格数据
      vendorPaymentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        provide: null,
        financeCode: null,
        taxRed: null,
        platformMoney: null,
        payableMoney: null,
        unpaidMoney: null,
        valuationTax: null,
        status: null,
        createTime: ""
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        financeCode: [
          { required: true, message: '请输入财务编号', trigger: 'blur' }
        ],
        provide: [
          { required: true, message: '请输入供应商名称', trigger: 'blur' }
        ],
        taxRed: [
          { required: true, message: '请输入含税红冲', trigger: 'blur' }
        ],
        platformMoney: [
          { required: true, message: '请输入平台金额', trigger: 'blur' }
        ],
        payableMoney: [
          { required: true, message: '请输入应付金额', trigger: 'blur' }
        ],
        unpaidMoney: [
          { required: true, message: '请输入未付金额', trigger: 'blur' }
        ],
        valuationTax: [
          { required: true, message: '请输入含税估价', trigger: 'blur' }
        ]

      },
      closingStatus: [
        { value: '未结算', label: 0 },
        { value: '结算', label: 1 },
      ],
      dateTime: [],
      allMoney: '',
      deptName: "",
      provideShow: false,
      dialogVisible: false,
      rzDisabled: false,
      rz: '入账',
      checked: false,
      checked1: false,
      checked2: false,
      rzLoading: false,
      loadingbtn: false,
      ShowVisible: false
    };
  },
  created() {
    this.FormData();
    this.wareList();
    const User = localStorage.getItem('User');
    this.deptName = JSON.parse(User).dept ? JSON.parse(User).dept.deptName : '';
    if (this.deptName !== '物资公司') {
      this.queryParams.provide = this.deptName;
      this.provideShow = true;
    } else {
      this.queryParams.provide = "";
      this.provideShow = false;
    }

    this.getList();

  },
  methods: {
    // 导入
    importExcelFun() {
      this.Upload();
    },
    Upload() {
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      let Time = formattedStartDate;
      const file = document.createElement('input');
      file.accept = '.xls, .xlsx'; // 允许上传的文件类型
      file.type = 'file';
      file.click();
      let _this = this;
      file.onchange = function (target) {
        var selectedFile = file.files[0];
        let param = new FormData(); // 创建form对象
        param.append('file', selectedFile); // 通过append向form对象添加数据
        _this.loadingbtn = true;
        if (_this.vendorPaymentList.length > 0) {
          _this.$confirm('已经存在数据，是否需要覆盖?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            showClose: false,
            closeOnClickModal: false,
            type: 'warning'
          }).then(() => {
            if (_this.loadingbtn) {
              _this.ShowVisible = true;
            }
            excelUpload(param, Time)
              .then(data => {
                let res = data.data;
                if (res.code === 200) {
                  setTimeout(() => {
                    _this.$message.success('导入成功');
                  }, 500);
                  _this.getList();
                } else {
                  setTimeout(() => {
                    _this.$message.error(res.info);
                  }, 500);
                }
              })
              .finally(() => {
                _this.loadingbtn = false;
                if (!_this.loadingbtn) {
                  _this.ShowVisible = false;
                }
              });
          }).catch(() => {
            _this.$message({
              type: 'info',
              message: '取消数据覆盖'
            });
            _this.loadingbtn = false;
          });
        } else {
          if (_this.loadingbtn) {
            _this.ShowVisible = true;
          }
          excelUpload(param, Time)
            .then(data => {
              let res = data.data;
              if (res.code === 200) {
                setTimeout(() => {
                  _this.$message.success('导入成功');
                }, 500);
                _this.getList();
              } else {
                setTimeout(() => {
                  _this.$message.error(res.info);
                }, 500);
              }
            })
            .finally(() => {
              _this.loadingbtn = false;
              if (!_this.loadingbtn) {
                _this.ShowVisible = false;
              }
            });
        }
      };
    },

    // 导入数据
    importUpData() {
      this.loadingbtn = true;
      getMonthlyStorageOutApi({createTime: this.queryParams.createTime}).then(res => {
      if(res.code == 200) {
          this.$message.success("导入完成，请确认是否正确")
      } else {
        this.$message.error(res.msg)
      }
      }).finally(() => {
        this.loadingbtn =  false;
      })
    },

    // 入账
    RecordedClick() {
      if (this.allMoney == 0) {
        this.$message.warning('本月开票总金额为0,不得入账');
      } else {
        this.dialogVisible = true;
        this.checked = false;
        this.checked1 = false;
        this.checked2 = false;
      }
    },
    // 取消入账
    rzCancel() {
      this.dialogVisible = false;
      this.wareList();
    },
    // 确认入账
    rzAffirm() {
      if (this.checked === true && this.checked1 === true && this.checked2 === true) {
        // 将日期字符串转换为日期对象
        const dateObj = new Date(this.dateTime);

        // 获取年份和月份
        const year = dateObj.getFullYear();
        const month = dateObj.getMonth() + 1;

        // 格式化月份为两位数
        const formattedMonth = month < 10 ? `0${month}` : `${month}`;

        // 格式化日期
        const formattedStartDate = `${year}-${formattedMonth}`;
        let Time = formattedStartDate;
        this.rzLoading = true;
        insertByProvideRevords(Time).then(rst => {
          if (rst.code === 200) {
            this.$message.success(rst.msg);
            // this.$store.commit('tagsView/SET_KP_STATUS', 1);
          } else {
            this.$message.error(rst.msg)
          }
          this.wareList();
          this.dialogVisible = false;
          this.rzLoading = false;
        })
      } else {
        this.$message.warning('请勾选注意事项');
      }
    },
    // 是否入账接口
    wareList() {
      let provideWare = '配件库';
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      let Time = formattedStartDate;
      wareList(Time, provideWare).then(rst => {
        if (rst.code === 200) {
          if (rst.rows.length === 0) {
            console.log(3333);
            this.rz = "入账";
            this.rzDisabled = false
          } else if (rst.rows && rst.rows[0]) {
            console.log(4444);
            if (rst.rows[0].status == "0") {
              this.rz = "入账";
              this.rzDisabled = false
            } else if (rst.rows[0].status == "1") {
              this.rz = "入账中";
              this.rzDisabled = true;
            } else {
              this.rz = "已入账";
              this.rzDisabled = true;
            }
          }


        }
      })
    },
    /** 查询供应商付款列表 */
    getList() {
      this.loading = true;
      // 将日期字符串转换为日期对象
      const dateObj = new Date(this.dateTime);

      // 获取年份和月份
      const year = dateObj.getFullYear();
      const month = dateObj.getMonth() + 1;

      // 格式化月份为两位数
      const formattedMonth = month < 10 ? `0${month}` : `${month}`;

      // 格式化日期
      const formattedStartDate = `${year}-${formattedMonth}`;
      this.queryParams.createTime = formattedStartDate;

      listVendorPayment(this.queryParams).then(response => {
        let summoney = localStorage.getItem('summoney');
        this.allMoney = summoney ? parseFloat(summoney).toFixed(2) : 0;
        this.vendorPaymentList = response.rows;
        this.vendorPaymentList.forEach((item, index) => {
          item.index = (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1;
        })
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createTime: null,
        provide: null,
        financeCode: null,
        taxRed: null,
        platformMoney: null,
        payableMoney: null,
        unpaidMoney: null,
        valuationTax: null,
        status: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
      if (this.queryParams.provide !== "") {
        this.rzDisabled = true;
      } else {
        this.wareList();
      }

    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.FormData();
      this.handleQuery();
      this.wareList()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加供应商付款";
    },
    /** 仓库详情操作 */
    handleUpdate(provide) {
      this.$router.push({
        name: 'WarehouseDetail', query: {
          provide: provide, dateTime: this.queryParams.createTime
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateVendorPayment(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVendorPayment(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 产品详情操作 */
    handleDelete(provide) {
      this.$router.push({
        name: 'PartsWarehouse', query: {
          provide: provide, dateTime: this.queryParams.createTime, fromMenu: true
        },
      });

    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/provideAllRecords/export', {
        ...this.queryParams
      }, `供应商付款${this.queryParams.createTime}.xlsx`)
    },
    // 日期转换
    FormData() {
      // 定义一个函数,用于格式化日期为"yyyy-MM"
      const formatDate = date => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        return `${year}-${month}`;
      };

      // 获取当前日期
      const currentDate = new Date();

      // 获取当前月的上个月
      const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1);

      // 设置dateTime的初始值为上个月,并格式化为"yyyy-MM"
      this.dateTime = formatDate(lastMonth);
    },
    // 数字转换
    formatNumber(value) {
      if (value) {
        let [integerPart, decimalPart] = value.toString().split('.');
        let formattedNumber = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',') + '.' + decimalPart.slice(0, 3);
        return formattedNumber;
      }

    },
    // 日期改变刷新表格
    dateChange() {
      this.queryParams.pageNum = 1;
      this.getList();
      if (this.queryParams.provide !== "") {
        this.rzDisabled = true;
      } else {
        this.wareList();
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.textNum {
  float: right;
}

.textTs {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-top: 10px;

  .text {
    margin-top: 20px;
    color: red;
  }

  .pagination-container {
    width: 50%;
  }
}

.textNuM {
  float: right;
  margin-right: 15px;
  font-size: 15px;
  margin-top: 3px;
  color: #c0c4cc;

  .kpNum {
    font-weight: 600;
    color: red;
  }
}
</style>
